package com.example.androidlearning2200.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import com.example.androidlearning2200.ChatActivity1;
import com.example.androidlearning2200.R;

import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 在后台监听消息的Service，收到消息后，发送通知Notification
 */
public class MessageService extends Service {

    private ScheduledExecutorService executorService;
    private int counter;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.d("MessageService", "onBind");
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("MessageService", "onCreate");
        executorService = Executors.newScheduledThreadPool(1);
        counter = 0;
    }

    /**
     * 当Context.startService时，会触发该方法
     *
     * @param intent
     * @param flags
     * @param startId
     * @return
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("MessageService", "onStartCommand");
        // 通过线程池执行定时任务，模拟与服务器建立长连接通信
        executorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                counter += 1;
                // counter能够被60整除，表示收到消息
                if (counter % 60 == 0) {
                    Log.d("COUNTER", "收到消息:" + counter);
                    // 收到消息后，通过通知提醒用户
                    sendNotificationHigh();
                }
                Log.d("COUNTER", "Counter:" + counter);
            }
        }, 1, 1, TimeUnit.SECONDS);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("MessageService", "onDestroy");
    }

    /**
     * 发送通知
     */
    private void sendNotificationHigh() {
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        // 通知渠道，给通知的重要性进行分类，方便用户有选择的接收通知
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel("MessageService" + 100, "重要通知", NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(notificationChannel);
        }
        Intent intent = new Intent(this, ChatActivity1.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 1000, intent, PendingIntent.FLAG_IMMUTABLE);
        Notification notification = new NotificationCompat.Builder(this, "MessageService" + 100)
                .setContentTitle("通知标题")
                .setContentText("通知内容通知内容通知内容通知内容通知内容")
                .setSmallIcon(android.R.mipmap.sym_def_app_icon)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.avatar))
                .setWhen(System.currentTimeMillis())
                .setAutoCancel(true)
                .setContentIntent(pendingIntent)
                .build();
        notificationManager.notify(new Random().nextInt(), notification);
    }

}
